import java.util.concurrent.CountDownLatch;

/**
 * 2 懒汉式（在类加载时不初始化，可以延时加载）
 * （1）懒汉式（线程不安全，但效率高）
 *
 * @author agstar
 * @date 2019/7/3 10:14
 */
public class LazyInstance {

    private static LazyInstance instance = null;

    /**
     * 构造函数私有化
     */
    private LazyInstance() {
        if (instance != null) {
            throw new RuntimeException("单例构造器禁止反射!");
        }
    }

    /**
     * 提供一个全局的静态方法
     */
    public static LazyInstance getInstance() {
        if (instance == null) {
            instance = new LazyInstance();
        }
        return instance;
    }

    public static void main(String[] args) {
        int count = 2000;
        CountDownLatch latch = new CountDownLatch(count);

        /*for (int i = 0; i < count; i++) {
            new Thread(() -> {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LazyInstance lazyone = LazyInstance.getInstance();
                System.out.println(lazyone);
            }).start();
            latch.countDown();
        }*/
        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                LazyInstance lazyone = LazyInstance.getInstance();
                System.out.println(lazyone);
            }).start();
        }
    }

}
